<template>
	<view>
		<button @tap="connectSocket">连接socket</button>
		<button @tap="closeSocket">断开socket</button>
		<button @tap="sendSocket">发送测试消息</button>
	</view>
</template>

<script setup lang="ts">
	import { onLoad } from '@dcloudio/uni-app'
	import { toRefs } from 'vue';
	import { useLoginStore } from '@/store/login'
	
	const loginStore = useLoginStore()
	const { token } = toRefs(loginStore)
	
	let socketMessage = ''
	const connectSocket = () => {
		uni.connectSocket({
			url: `ws://localhost:8081/${token.value}`
		})
	}
	const closeSocket = () => {
		uni.closeSocket()
	}
	const sendSocket = () => {
		uni.sendSocketMessage({
			data: JSON.stringify({
				type: 1,
				msg: '这是一条测试消息'
			})
		})
	}
	
	uni.onSocketOpen(function (res) {
		console.log('WebSocket连接已打开')
	});
	
	uni.onSocketError(function (res) {
	  console.log('WebSocket连接打开失败，请检查！');
	});
	uni.onSocketMessage(function (res) {
	  console.log('收到服务器内容：' + res);
	})
	uni.onSocketClose(function (res) {
	  console.log('WebSocket 已关闭！');
	});
	
	
	
	
	
	onLoad((query?: AnyObject) => {
		console.log('query:', query)
	})
	
	defineExpose({
		connectSocket,
		closeSocket
	})
</script>

<style>

</style>
